import 'package:azring/pages/status/status_logic.dart';
import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import '../gen/assets.gen.dart';

/// 压力图表组件
class PressureChart extends StatelessWidget {
  const PressureChart({super.key});

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: 120.h,
      child: Obx(() {
        // 获取controller并访问响应式变量，确保Obx能监听到变化
        final statusController = Get.find<StatusLogic>();
        final stressList = statusController.state.todayStressList;
        final emotionalRecords = statusController.state.emotionalStateList;
        final selectedDate = statusController.state.selectedDate.value;
        
        // 强制访问这些响应式变量，确保Obx订阅它们
        final _ = stressList.length;
        final __ = emotionalRecords.length;
        final ___ = selectedDate.day; // 监听日期变化
        
        final spots = _getPressureSpots();

        // 如果没有数据，显示提示信息
        if (spots.isEmpty) {
          return Center(
            child: Text(
              '暂无压力数据',
              style: TextStyle(
                color: Colors.grey[400],
                fontSize: 14.sp,
              ),
            ),
          );
        }

        return Stack(
          clipBehavior: Clip.none, // 允许子元素溢出显示
          children: [
            // 图表
            LineChart(
              LineChartData(
                lineTouchData: const LineTouchData(
                  enabled: false, // 禁用触摸交互
                ),
                lineBarsData: [
                  LineChartBarData(
                    spots: spots,
                    isCurved: true,
                    curveSmoothness: 0.35, // 增加曲线平滑度，让数据更曲折
                    isStrokeCapRound: true,
                    barWidth: 3,
                    color: const Color(0xffED5C2F),
                    belowBarData: BarAreaData(
                      show: true,
                      color: const Color(0xffED5C2F).withValues(alpha: 0.1),
                    ),
                    dotData: const FlDotData(
                      show: false,
                      
                    ),
                  ),
                ],
                minX: 0,
                maxX: 24,
                minY: 0,
                maxY: 100,
                titlesData: FlTitlesData(
                  leftTitles: AxisTitles(
                    sideTitles: SideTitles(
                      showTitles: true,
                      reservedSize: 30.w,
                      getTitlesWidget: (value, meta) {
                        return Text(
                          value.toInt().toString(),
                          style: TextStyle(
                            color: Colors.grey[400],
                            fontSize: 10.sp,
                          ),
                        );
                      },
                      interval: 25,
                    ),
                  ),
                  rightTitles: const AxisTitles(
                    sideTitles: SideTitles(showTitles: false),
                  ),
                  bottomTitles: AxisTitles(
                    sideTitles: SideTitles(
                      showTitles: true,
                      reservedSize: 25.h,
                      getTitlesWidget: (value, meta) {
                        String text = '';
                        // 只显示三个时间点：00:00, 12:00, 24:00
                        if (value == 0) {
                          text = '00:00';
                        } else if (value == 12) {
                          text = '12:00';
                        } else if (value == 24) {
                          text = '24:00';
                        }

                        return Text(
                          text,
                          style: TextStyle(
                            color: Colors.grey[400],
                            fontSize: 10.sp,
                          ),
                        );
                      },
                      interval: 12, // 每12小时显示一个时间标签
                    ),
                  ),
                  topTitles: const AxisTitles(
                    sideTitles: SideTitles(showTitles: false),
                  ),
                ),
                gridData: const FlGridData(
                  show: false, // 禁用网格线
                ),
                borderData: FlBorderData(
                  show: false,
                ),
              ),
            ),

            // 情绪图标覆盖层 - 显示所有情绪记录
            if (emotionalRecords.isNotEmpty)
              Stack(
                children: emotionalRecords.map((record) {
                  // 解析时间 "HH:mm"
                  final timeParts = record.recordTime.split(':');
                  if (timeParts.length != 2) {
                    return const SizedBox.shrink();
                  }

                  final hour = int.tryParse(timeParts[0]) ?? 0;
                  final minute = int.tryParse(timeParts[1]) ?? 0;
                  final recordDateTime = DateTime(
                    DateTime.now().year,
                    DateTime.now().month,
                    DateTime.now().day,
                    hour,
                    minute,
                  );

                  // 计算情绪图标在图表上的位置
                  final timePosition = _getTimePosition(recordDateTime);
                  final pressureValue = _getPressureValueAtTime(recordDateTime);
                  final yPosition = _getYPosition(pressureValue);

                  print('🎭 Emoji位置计算: 时间=$hour:$minute, X=$timePosition, Y=$yPosition, 压力值=$pressureValue');

                  // 根据情绪状态获取对应的图片资源
                  final moodImage = _getMoodImageByState(record.emotionalState);

                  return Positioned(
                    left: timePosition - 20.w,
                    top: yPosition - 20.h,
                    child: Container(
                      width: 40.w,
                      height: 40.h,
                      decoration: BoxDecoration(
                        shape: BoxShape.circle,
                        boxShadow: [
                          BoxShadow(
                            color: Colors.black.withValues(alpha: 0.3),
                            blurRadius: 8,
                            offset: const Offset(0, 2),
                          ),
                        ],
                      ),
                      child: moodImage,
                    ),
                  );
                }).toList(),
              ),
          ],
        );
      }),
    );
  }

  /// 获取压力数据点 - 使用真实的压力数据
  List<FlSpot> _getPressureSpots() {
    try {
      final statusController = Get.find<StatusLogic>();
      final stressList = statusController.state.todayStressList;


      if (stressList.isEmpty) {
        return [];
      }

      // 将压力列表数据转换为图表数据点
      List<FlSpot> spots = _processStressListToSpots(stressList);

      return spots;
    } catch (e) {
      return [];
    }
  }

  /// 将压力列表转换为图表数据点（支持null值）
  List<FlSpot> _processStressListToSpots(List<int?> stressList) {
    List<FlSpot> spots = [];

    // 数据说明：288个数据点，5分钟间隔，覆盖24小时
    // 每小时 = 12个数据点 (60分钟 ÷ 5分钟 = 12)
    // 总计：24小时 × 12个/小时 = 288个数据点

    // 数据处理：每小时取一个数据点显示在图表上（24个显示点）
    const int intervalMinutes = 60; // 图表显示间隔（1小时）
    const int dataPointsPerInterval =
        intervalMinutes ~/ 5; // 每个显示间隔包含多少个原始数据点（12个）

    int validHoursCount = 0;
    for (int i = 0; i < 24; i++) {
      // 24小时，每小时一个点
      final double timeHour = i.toDouble(); // 时间点：0, 1, 2, ..., 23

      // 计算对应的原始数据索引范围
      final int startIndex = i * dataPointsPerInterval;
      final int endIndex = startIndex + dataPointsPerInterval;

      // 收集该时间段内的有效数据
      List<int> validValues = [];
      for (int j = startIndex; j < endIndex && j < stressList.length; j++) {
        final value = stressList[j];
        if (value != null && value > 0) {
          validValues.add(value);
        }
      }

      // 如果有有效数据，计算平均值并添加到图表
      if (validValues.isNotEmpty) {
        final double avgValue =
            validValues.reduce((a, b) => a + b) / validValues.length;
        final double clampedValue = avgValue.clamp(0.0, 100.0);
        spots.add(FlSpot(timeHour, clampedValue));
        validHoursCount++;
      }
      // null值或无效值的时间段不添加数据点，这样曲线会在这些位置断开
    }

    return spots;
  }



  /// 根据时间获取X轴位置
  double _getTimePosition(DateTime time) {
    final hour = time.hour + time.minute / 60.0;
    // 图表实际宽度需要减去左右padding和Y轴标签宽度
    final chartWidth = 280.w; // 调整图表宽度以匹配实际渲染区域
    final leftPadding = 35.w; // Y轴标签预留空间
    return leftPadding + (hour / 24.0) * chartWidth;
  }

  /// 根据时间获取压力值（从API数据中查找）
  double _getPressureValueAtTime(DateTime time) {
    try {
      final statusController = Get.find<StatusLogic>();
      final stressList = statusController.state.todayStressList;

      if (stressList.isEmpty) {
        return 50.0; // 默认中间位置
      }

      // 计算时间对应的数据索引
      // API返回288个数据点，每5分钟一个点
      final totalMinutes = time.hour * 60 + time.minute;
      final dataIndex = (totalMinutes / 5).floor(); // 每5分钟一个数据点

      // 确保索引在有效范围内
      if (dataIndex >= 0 && dataIndex < stressList.length) {
        final value = stressList[dataIndex];
        if (value != null && value > 0) {
          return value.toDouble();
        }
      }

      // 如果当前时间点没有数据，尝试查找附近的数据点
      // 向前查找最多12个数据点（1小时）
      for (int offset = 1; offset <= 12; offset++) {
        final prevIndex = dataIndex - offset;
        if (prevIndex >= 0 && prevIndex < stressList.length) {
          final value = stressList[prevIndex];
          if (value != null && value > 0) {
            return value.toDouble();
          }
        }
      }

      // 如果还是没找到，返回默认值
      return 50.0;
    } catch (e) {
      print('❌ 获取压力值失败: $e');
      return 50.0;
    }
  }

  /// 根据压力值获取Y轴位置
  double _getYPosition(double pressureValue) {
    final chartHeight = 120.h;
    final topPadding = 10.h; // 顶部预留空间
    final bottomPadding = 25.h; // 底部时间标签预留空间
    final effectiveHeight = chartHeight - topPadding - bottomPadding;

    // 压力值范围是0-100，Y轴是从上到下的
    // 确保压力值在有效范围内
    final clampedValue = pressureValue.clamp(0.0, 100.0);
    return topPadding + effectiveHeight - (clampedValue / 100.0) * effectiveHeight;
  }

  /// 根据情绪状态值获取对应的图片资源
  Widget _getMoodImageByState(String emotionalState) {
    switch (emotionalState) {
      case '1':
        return Assets.status.veryUnhappy.image(width: 40.w, height: 40.h);
      case '2':
        return Assets.status.littleUnhappy.image(width: 40.w, height: 40.h);
      case '3':
        return Assets.status.noneFeeling.image(width: 40.w, height: 40.h);
      case '4':
        return Assets.status.littleHappy.image(width: 40.w, height: 40.h);
      case '5':
        return Assets.status.veryHappy.image(width: 40.w, height: 40.h);
      default:
        return Assets.status.noneFeeling.image(width: 40.w, height: 40.h);
    }
  }
}
